import {emit, on} from "../../../utils/event";
import {showToast} from "../../../utils/tool";
import orderRefundService from "../../../service/orderRefund";
import {simplePost} from "../../../utils/request";

const app = getApp()
const global = app.globalData

Page({
    data: {
        nav:{
            title:'售后申请'
        },
        subLoading:false,
        options:{},
        order:null,
        info:{
            itemIdArr:[],
            amount:0,
        },
        imageUrl:global.imageUrl,
        refundTypes: orderRefundService.refundTypes,
    },
    onLoad: function (options={}) {
        this.init(options)
    },

    refundTypeChange(e){
        const {value} = e.detail
        this.setData({
            [`info.refund_type`]: value,
        })
    },
    allChecked(){
        const {order} = this.data
        const checkedArr = order.items.map(item => {
            return item.id
        })
        this.setData({
            [`info.itemIdArr`]:checkedArr,
        })
        this.computedAmount(checkedArr)
    },
    goodsChange(e){
        const {value} = e.detail
        this.setData({
            [`info.itemIdArr`]:value,
        })
        this.computedAmount(value)
    },

    computedAmount(itemIdArr){
        let amount = 0
        const {order} = this.data
        for (let id of itemIdArr){
            const it = order.items.find(item => item.id == id)
            if (it){
                amount += it.pay_price*100
            }

        }
        this.setData({
            [`info.amount`]: parseFloat(amount/100)
        })
    },

    submit: function (e) {
        const {order, info} = this.data
        const {value} = e.detail

        const post = {
            order_id:order.id,
            ...info,
            ...value
        }

        if (!post.refund_type){
            showToast("请选择退款类型")
            return;
        }

        if (post.itemIdArr.length==0){
            showToast("请选择退款商品")
            return;
        }

        if (!post.note){
            showToast("请描述退款原因")
            return;
        }

        this.setData({
            subLoading: true,
        })

        simplePost("/order/refundApply",post).then(r => {
            this.setData({
                show:false,
            })
            showToast("申请成功", {
                timeout:() => {
                    wx.navigateBack()
                }
            })
        }).catch(err => {
            this.setData({
                subLoading: false,
            })
        })

    },

    async init(options){

        // 监听页面跳转事件
        on(this, 'fromOrderShowEvent', ({order}) => {
            this.setData({
                options,
                order,
            })
        })
    }
});
